/*
 * File:  CameraUtil.java
 * Copyright (c) $2018 3N CTO Co.,Ltd. All rights reserved
 * Date:  18-5-14 下午6:04
 * Version:  V1.0
 *
 */

package com.lyshop.guiyingshanding.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;

import androidx.core.content.FileProvider;


import com.lyshop.guiyingshanding.BuildConfig;
import com.lyshop.guiyingshanding.application.MyApplication;
import com.lyshop.guiyingshanding.bean.CropBean;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 相机相册工具类
 * 作者： JairusTse
 * 日期： 18/5/14 18:03
 */
public class CameraUtil {

    /**
     * 启动相机
     *
     * @param activity
     * @param file 拍照后保存的相片文件
     * @param requestCode 请求码
     */
    public static void openCamera(Activity activity, File file, int requestCode) {
        if (!isHaveCame(MediaStore.ACTION_IMAGE_CAPTURE)) {
            Toast.makeText(activity, "该手机没有安装相机", Toast.LENGTH_SHORT).show();
            return;
        }
        //指定相机意图
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //如果TargetSdkVersion >= 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri photoUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + "" +
                    ".fileprovider", file);
            //申请权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //设置相片保存的地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        } else {
            //设置相片保存的地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

        }
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 启动相册
     *
     * @param activity
     * @param requestCode 请求码
     */
    public static void openAlbum(Activity activity, int requestCode) {
        //指定相册意图
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // 设置文件类型
        intent.setType("image/*");
        activity.startActivityForResult(intent, requestCode);
    }


    /**
     * 启动裁剪
     *
     * @param activity
     * @param cropBean
     * @param requestCode
     */
    public static void openCrop(Activity activity, CropBean cropBean, int requestCode) {
        if (cropBean == null) {
            Toast.makeText(activity, "cropBean不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cropBean.inputUri == null) {
            Toast.makeText(activity, "裁剪图片inputUri不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        //配置一系列裁剪参数
        intent.putExtra("outputX", cropBean.outputX);
        intent.putExtra("outputY", cropBean.outputY);
        intent.putExtra("scale", cropBean.scale);
        intent.putExtra("aspectX", cropBean.aspectX);
        intent.putExtra("aspectY", cropBean.aspectY);
        intent.putExtra("outputFormat", cropBean.outputFormat);
        intent.putExtra("return-mList", cropBean.isReturnData);

        //如果TargetSdkVersion >= 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //申请权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //将数据Uri转化成FileProvider的Uri
            File dataFile = new File(UriUtil.getPath(cropBean.inputUri));
            cropBean.inputUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID +
                    ".fileprovider", dataFile);
        }
        //设置要裁剪的图片Uri
        intent.setDataAndType(cropBean.inputUri, "image/*");
        // 如果不需要返回Btimap，则必须指定图片保存的Uri
        if (!cropBean.isReturnData) {
            if (cropBean.outputUri == null) {
                Toast.makeText(activity, "请指定保存裁剪图片地址：outputUri", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropBean.outputUri);

        activity.startActivityForResult(intent, requestCode);

    }

    /**
     * 判断意图是否存在
     */
    public static boolean isHaveCame(String intentName) {
        PackageManager packageManager = MyApplication.getApplication().getPackageManager();
        Intent intent = new Intent(intentName);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager
                .MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);
            base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                Bitmap bitmap1 = resizeBitmap(bitmap, 800, 600);
                bitmap1.compress(Bitmap.CompressFormat.JPEG, 50, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Bitmap resizeBitmap(Bitmap bitmap, int w, int h)
    {

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float scaleWidth = ((float) w) / width;
        float scaleHeight = ((float) h) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
                height, matrix, true);
        int width1 = resizedBitmap.getWidth();
        return resizedBitmap;
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }
}
